﻿using System.Net.WebSockets;
using System.Text;

namespace ClientWebSocketDemo.WebApi.Models
{
    public interface IChannel
    {
        Task SendAsync(string serviceUniqueId);
    }

    class WebsocketChannel : IChannel
    {
        private IConfigClient _client;

        public WebsocketChannel(IConfigClient client)
        {
            _client = client;
        }

        private ClientWebSocket Websocket
        {
            get
            {
                return _client.WebSocket;
            }
        }

        public async Task SendAsync(string id)
        {
            if (Websocket.State == WebSocketState.Open)
            {
                var msg = $"s:ping:{id}";
                var data = Encoding.UTF8.GetBytes(msg);
                await Websocket.SendAsync(new ArraySegment<byte>(data, 0, data.Length), WebSocketMessageType.Text, true,
                        CancellationToken.None).ConfigureAwait(false);
            }
        }
    }

    public class HeartbeatChannelPicker
    {
        private IConfigClient _client;
        private IChannel _wsChan;

        public HeartbeatChannelPicker(IConfigClient client)
        {
            _client = client;
            _wsChan = new WebsocketChannel(_client);
        }

        public IChannel Pick()
        {
            return _wsChan;
        }
    }
}
